package com.programmercarl.backtracking;

/**
 * https://leetcode.cn/problems/sudoku-solver/
 * 解数独  二维递归
 *
 * @author yulongtian
 * @create 2025-02-02 10:45
 */
public class Test15 {
    public static void main(String[] args) {

    }

    public void solveSudoku(char[][] board) {
        backtrack(board);
    }

    public boolean backtrack(char[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] != '.') {
                    continue;
                }
                for (int k = 1; k <= 9; k++) {
                    if (check(board, i, j, (char) (k + '0'))) {
                        // 满足
                        board[i][j] = (char) (k + '0');
                        if (backtrack(board)) {
                            return true;
                        }
                        board[i][j] = '.';
                    }
                }
                return false;
            }
        }
        return true;
    }

    public boolean check(char[][] board, int row, int col, char val) {
        // 行
        for (int j = 0; j < board[0].length; j++) {
            if (board[row][j] == val) {
                return false;
            }
        }

        // 列
        for (int i = 0; i < board.length; i++) {
            if (board[i][col] == val) {
                return false;
            }
        }

        // 3 x 3
        int startRow = (row / 3) * 3;
        int startCol = (col / 3) * 3;
        for (int i = startRow; i < startRow + 3; i++) {
            for (int j = startCol; j < startCol + 3; j++) {
                if (board[i][j] == val) {
                    return false;
                }
            }
        }
        return true;
    }

}
